package com.ilioili.appframe;
import java.io.File;
import java.util.ArrayList;

import util.bitmap.ImgPool;
import util.bitmap.FileUtil;
import util.bitmap.Img;
import util.bitmap.ImgView;
import util.bitmap.TestPictures;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;

public class ListViewWithPictures extends BaseActivity {

	final ImgPool imgPool = new ImgPool(){
		@Override
		public void bitmapDecoded(Img<?> img, View v) {
			ImgView iv = (ImgView) v;
			iv.setLayoutType(ImgView.TYPE_FIXED_WIDTH_WITH_SCALED_HEIGHT);
			iv.setImageBitmap(img.getBitmap());
			iv.startAnimation(getScaleAnimation());
		}
		
		public Animation getScaleAnimation(){
//			Animation a = new ScaleAnimation(0, 1, 0, 1, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
			Animation a = AnimationUtils.loadAnimation(ListViewWithPictures.this, android.R.anim.fade_in);
			a.setDuration(1000);
			return a;
		}

		@Override
		public void bitmapNotDecoded(View bindedView) {
			ImgView iv = (ImgView) bindedView;
			iv.setImageBitmap(null);
		}
	};
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		imgPool.shutdown();
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FileUtil.init(getApplication());
		final ArrayList<Img<?>> imgList = new ArrayList<Img<?>>();
		int width = getResources().getDisplayMetrics().widthPixels;
		File fileDir = FileUtil.getFileDir();
		File cacheDir = FileUtil.getCacheDir();
		for(int i=0; i<TestPictures.URLS.length; i++){
			Img img = new Img(cacheDir, fileDir, TestPictures.URLS[i]);
				img.setSizeBaseOnWidth(width);
//			img.setSize(width, width/3);
//				img.setSizeBaseOnWidth(300);
			imgList.add(img);
		}
		
		ListView lv = new ListView(this);
		setContentView(lv);
		lv.setAdapter(new BaseAdapter() {
			
			
			@Override
			public View getView(int position, View v, ViewGroup parent) {
				ImgView iv = (ImgView) v;
				if(iv==null){
					iv = new ImgView(ListViewWithPictures.this);
					iv.setScaleType(ScaleType.CENTER_CROP);
					iv.setRatioBaseOnWidth(1);
				}
				imgPool.bind(imgList.get(position), iv);
				return iv;
			}
			
			@Override
			public long getItemId(int position) {
				return 0;
			}
			
			@Override
			public Object getItem(int position) {
				return null;
			}
			
			@Override
			public int getCount() {
				return imgList.size();
			}
		});
	}

}
